/**查找分页控件 -> 请求下一页 -> 增删元素 -> 加载在页面 */
async function loadNextPage() {
  let [lastNrPage] = [...document.getElementsByClassName('bottem2')].slice(-1)
  let url = lastNrPage.querySelector('a:nth-child(3)').href

  const response = await fetch(url)

  let host = window.location.host
  let isUseGbk = ['www.ddyveshu.cc'].includes(host)
  let customHandler =
    {
      'www.ddyveshu.cc': handleDyveshuContent,
    }[host] || (() => {})

  const decoder = new TextDecoder(isUseGbk ? 'gbk' : 'utf8')
  const html = decoder.decode(await response.arrayBuffer())
  let div = document.createElement('div')
  div.innerHTML = html

  let alink = document.createElement('a')
  alink.href = url
  alink.innerText = '本页'
  for (let pageClassName of ['.bottem1', '.bottem2']) {
    let pageDom = div.querySelector(pageClassName)
    if (pageDom.querySelectorAll('a').length >= 4) {
      pageDom.insertBefore(alink.cloneNode(true), pageDom.children[3])
      pageDom.removeChild(pageDom.children[3])
    } else {
      pageDom.appendChild(alink.cloneNode(true))
    }
  }

  div.querySelector('.box_con').style.borderLeftWidth = '0'
  div.querySelector('.box_con').style.borderRrightWidth = '0'
  div.querySelector('.box_con').style.borderBottomWidth = '0'

  $chromePlugin.cleanPage(div, ['.ywtop', '.header', '.nav', '.con_top', '.lm', '.footer', '#content_1', '#content_2', '.readtj'])

  customHandler(div)

  let [lastContent] = [...document.getElementsByClassName('box_con')].slice(-1)
  lastContent.appendChild(div)
  return { div, url }
}

/**www.ddyveshu.cc 个性样式修正*/
function handleDyveshuContent(div) {
  div.querySelector('.content_read').style.width = '100%'
  handleAddSpace(div)
}

function handleAddSpace(dom = document) {
  let el = null
  if (['www.ddyveshu.cc'].includes(location.host)) {
    el = dom.querySelector('#content')
  }
  addSpace(el)
}

/**添加段落之间的间隔， 提升阅读体验 */
function addSpace(dom) {
  if (!dom) return
  let brNodeList = dom.querySelectorAll('br')
  // 抽查某个br的下一个节点是否是br 来判断是否需要执行后续遍历添加br的操作
  if (brNodeList.length > 8 && $chromePlugin.getNextNodeName(brNodeList[6]) == 'BR') return
  // 遍历添加第二个br元素
  for (let i = 0; i < brNodeList.length; i++) {
    let brNode = brNodeList[i]
    if ($chromePlugin.getNextNodeName(brNode) == 'BR') continue
    dom.insertBefore(document.createElement('br'), brNode)
  }
}

$chromePlugin.loadQueueFn.push(handleAddSpace)

/**获取正确的书链接 */
function getBookLink() {
  let { href, host, origin } = location
  if (host == 'www.xs55.org') {
    let result = href.match(/read\/(\w+)/)
    if (result && result.length) {
      return `${host}/txt${result[1]}.html`
    }
    return location.href
  }
  return $chromePlugin._getBookLink()
}

/**从页面获取书名 */
function getBookName() {
  let dom = null
  if (document.querySelector('#info')) {
    return document.querySelector('#info h1').innerText
  }

  if (document.body.getAttribute('article-name')) {
    return document.body.getAttribute('article-name')
  }

  dom = document.querySelector('.con_top>a:nth-of-type(3)')
  if (dom && dom.innerText) {
    return dom.innerText
  }

  dom = document.querySelectorAll('.con_top a')
  if (dom && dom.length) {
    return dom[dom.length - 1].innerText
  }
}

/**_addObserver传入targetSelector、chapterTitleSelector*/
function addObserver(dom = document, url = location.href) {
  let titleSelector = dom.querySelector('.bookname h1') ? '.bookname h1' : '.bookname'
  _addObserver('.box_con', titleSelector, dom, url)
}
